var StateThree = {
  preload: () => {
    game.load.image('gameover', "img/gameover.png")
    game.load.image('restart', 'img/restart.png')
    game.load.image('scoreBoard', 'img/scoreBoard.png')
    game.load.image('newScore', 'img/new.png')
    game.load.image('medal0', 'img/medal0.png')
    game.load.image('medal1', 'img/medal1.png')
    game.load.image('medal2', 'img/medal2.png')
    game.load.image('medal3', 'img/medal3.png')
  },

  create: () => {
    background = game.add.sprite(0, 0, 'background')
    background.scale.setTo(2, 2)
    ground = game.add.sprite(0, 920, 'ground')
    ground.scale.setTo(2, 2)
    gameover = game.add.sprite(game.world.centerX, game.world.centerY - 230, 'gameover')
    gameover.anchor = new Phaser.Point(.5, .5)

    highScore = localStorage.getItem("highScore")
    
    if (game.score > 0) {
      game.score -= 1
    }

    if(highScore == null){
      highScore = 0
    }else{
      highScore = parseInt(highScore)
    }
    


    newScore = game.add.sprite(-100, 370, "newScore")
    if (game.score > highScore){
      newScore.x = game.world.centerX + 40
      newScore.anchor = new Phaser.Point(.5, .5)
    }
    

    text = game.add.text(game.world.centerX + 110, 405, game.score, { font: "10 30px 'myfont'", fill: "#FFFFFF" });
    text2 = game.add.text(game.world.centerX + 115, 475, highScore, { font: "10 30px 'myfont'", fill: "#FFFFFF" });
    text.anchor = new Phaser.Point(.5, .5)
    text2.anchor = new Phaser.Point(.5, .5)

    restart = game.add.button(game.width / 2, game.height / 2 + 100, 'restart', function () {
      game.state.start('state_one')
    }, this)
    restart.anchor = new Phaser.Point(.5, .5)

    scoreBoard = game.add.sprite(game.world.centerX, game.world.centerY - 80, 'scoreBoard')
    scoreBoard.anchor = new Phaser.Point(.5, .5)
    scoreBoard.scale.setTo(1.6, 1.6)

    updateMedal(game.score)


    if (highScore == undefined) {
      highScore = 0
    }

    if (game.score > highScore) {
      localStorage.setItem("highScore", game.score, -1)
    }

  },

  update: () => {
    text.bringToTop()
    text2.bringToTop()
    newScore.bringToTop()
    medal.bringToTop()
    if (game.input.activePointer.isDown) {
      game.state.start("state_one")
    }
  }
}



function click() {
  game.state.start("state_one")
}

function updateMedal(score){
  if (score < 10){
    medal = game.add.sprite(game.world.centerX - 105 ,game.world.centerY - 75, "medal0")
  }else if (score >= 10 && score < 100){
    medal = game.add.sprite(game.world.centerX - 105 ,game.world.centerY - 75, "medal1")
  }else if (score >= 100 && score < 1000){
    medal = game.add.sprite(game.world.centerX - 105 ,game.world.centerY - 75, "medal2")
  }else if (score >= 1000){
    medal = game.add.sprite(game.world.centerX - 105 ,game.world.centerY - 75, "medal3")
  }
  medal.anchor = new Phaser.Point(.5, .5)
  medal.scale.setTo(1.6, 1.6)
}